package com.xw.unification.interfaces;

import com.xw.unification.entity.request.CopyOnReadHttpServletRequest;
import com.xw.unification.entity.request.RepeatableRequestDelegate;
import com.xw.unification.entity.request.RepeatableRequestRewriteContext;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;

/**
 * @author qiwei
 * @since v1.0.0
 */
@FunctionalInterface
public interface RepeatableRequestRewriter {

    /**
     * 重写 request
     * @param request       可重写的 request
     * @param response      响应
     * @param handlerMethod 处理方法
     * @param ctx           重写上下文
     * @return boolean 根据该值判断拦截器是否拦截该请求, true 则放行, false 则拦截
     */
    boolean rewrite(CopyOnReadHttpServletRequest request, HttpServletResponse response,
                    HandlerMethod handlerMethod, RepeatableRequestRewriteContext ctx);

    /**
     * 重写 request
     * @param request   可重写的 request
     * @param data      重写的数据内容
     * @return boolean 重写是否成功
     */
    static boolean rewrite(CopyOnReadHttpServletRequest request, byte[] data) {
        if (request == null) {
            return false;
        }
        return RepeatableRequestDelegate.rewrite(request, data);
    }
}
